using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Reflection;

namespace Serialization.Surrogates
{
    class GenericDictionarySurrogate : ISerializationSurrogate
    {
        #region ISerializationSurrogate Members

        public void GetObjectData(object obj, SerializationInfo info)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            ArrayList list = new ArrayList();
            IDictionary d = (IDictionary)obj;
            IDictionaryEnumerator e = d.GetEnumerator();
            while (e.MoveNext())
            {
                list.Add(e.Entry);
            }
            info.AddValue("List", list, list.GetType());
        }

        public void SetObjectData(object obj, SerializationInfo info, ISurrogateSelector selector)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (info == null)
            {
                throw new ArgumentNullException("info");
            }
            ConstructorInfo ctor = obj.GetType().GetConstructor(new Type[0]);
            if (ctor != null)
            {
                ctor.Invoke(obj, new object[0]);
            }

            ArrayList list = (ArrayList) info.GetValue("List");
            IDictionary d = (IDictionary)obj;
            foreach (DictionaryEntry entry in list)
            {
                d.Add(entry.Key, entry.Value);
            }
        }

        #endregion
    }
}
